import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
// Vue.use(Vant)
const routes = [

  {
    path: '/',
    component: () => import('../views/Main.vue'),
    children: [
      // path 为"空字符串"的子路由规则，叫做"默认子路由"
      { path: '', component: () => import('../views/Home.vue'), name: 'Home', meta: { isRecord: true, top: 0 } },
      { path: '/User', component: () => import('../views/User.vue'), name: 'User' }
    ]
  },

  {
    path: '/User/edit',
    name: 'user-edit',
    component: () => import('../views/editUserInfo.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/article/:artId',
    name: 'art-detail',
    component: () => import('../views/ArticleDetail/ArticleDetail.vue'),
    props: true,
    meta: { isRecord: true, top: 0 }
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})
const pagePathArr = ['/User', '/User/edit']
router.beforeEach((to, from, next) => {
  if (pagePathArr.indexOf(to.path) !== -1) {
    const token = localStorage.getItem('state')
    // console.log(token)
    if (token) {
      next()
    } else {
      // 模板字符串
      next(`/login?pre=${to.fullPath}`)
    }
  } else {
    next()
  }
})
// 全局后置钩子
router.afterEach((to, from) => {
  // 如果当前的路由的元信息中，isRecord 的值为 true
  if (to.meta.isRecord) {
    setTimeout(() => {
      // 则把元信息中的 top 值设为滚动条纵向滚动的位置
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})
export default router
